package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"path"
	"path/filepath"

	"github.com/sgoby/opencc"
)

func convertT2S(infile string, outdir string, cc *opencc.OpenCC) {
	// 输出文件
	dir, file := path.Split(filepath.ToSlash(infile))
	fmt.Println(dir, file)

	base := path.Base(file)
	ext := path.Ext(file)

	pre := base[0 : len(base)-len(ext)]

	if outdir == "" {
		outdir = dir
	}

	outfile := path.Join(path.Clean(filepath.ToSlash(outdir)), pre+".chs"+ext) // 简体
	fmt.Printf("writing to %v\n", outfile)
	outf, err := os.OpenFile(outfile, os.O_RDONLY|os.O_CREATE|os.O_APPEND, 0666)
	bufw := bufio.NewWriter(outf)
	defer outf.Close()

	inf, err := os.Open(infile)
	defer inf.Close()
	scanner := bufio.NewScanner(inf)
	for {
		if !scanner.Scan() {
			break
		}
		line := scanner.Text()

		stext, err := cc.ConvertText(line)

		if err != nil {
			fmt.Println(err)
			return
		}

		bufw.WriteString(stext)
		bufw.WriteString("\n")
	}
	bufw.Flush()

	if err != nil {
		fmt.Println(err)
	}

}

func main() {
	// -i 输入目录，-o 输出目录，-data opencc的数据目录
	var inDir string
	var outDir string
	flag.StringVar(&inDir, "i", "./", "数据输入目录")
	flag.StringVar(&outDir, "o", "./", "数据输出目录")

	flag.Parse()
	cc, err := opencc.NewOpenCC("t2s")
	if err != nil {
		fmt.Println(err)
		return
	}

	matches, _ := filepath.Glob(path.Join(inDir, "*.json"))
	for _, v := range matches {
		fmt.Printf("converting file %v\n", v)

		convertT2S(v, outDir, cc)
	}

}
